<template>
    <div class="tmpl">
        <!--1.0 商品列表-->
        <div class="row" v-for="(item,index) in shopCarList">
            <div class="left">
                <mt-switch class="switch" v-model="values[index]"></mt-switch>
            </div>
            <div class="center">
                <img :src="item.thumb_path" alt="" width="75" height="75">
            </div>
            <div class="right">
                <h4>{{item.title}}</h4>
                <span>￥{{item.sell_price}}</span>
                <div class="col">
                    <subNumber :initcount="item.count" :goodsid="item.id" class="subnumber" v-on:count="getCount"></subNumber>
                    <a @click="del(item.id)">删除</a>
                </div>
            </div>
        </div>
        <!--总计-->
        <div class="total">
            <div class="left">
                <h5>总计不含运费</h5>
                <span>已经勾选商品{{selectedCount}}件，总价￥{{settment}}元</span>
            </div>
            <div class="right">
                <mt-button class="settm" type="danger" size="normal">去结算</mt-button>
            </div>
        </div>
        {{values}}
    </div>
</template>
<style scoped>
    /*2.0 总计*/
    .total{
        padding:10px;
        background-color: rgba(1,1,1,0.1);
        margin-top: 10px;
        height: 80px;
    }
    .total h5{
        color: black;
        font-weight:bold;
        margin-bottom: 10px;
    }
    .total .left{
        width:70%;
        float: left;
    }
    .total .right{
        width:28%;
        float: right;
        height:80px;
    }
    .total .settm{
        margin-top: 10px;
    }
    /*1.0商品列表*/
    .row{
        display: flex;
        margin-top: 5px;
        border-bottom: 1px solid rgba(1,1,1,0.3);
        padding:5px;
    }
    .row .left{
        flex:0 0 20px;
    }
    .switch{
        margin-top: 20px;
    }
    .row .center{
        flex:0 0 75px;
        margin:0 15px;
    }
    .row .right{
        flex:1;
    }
    .row .right h4{
        color: #0094ff;
        padding:5px 0;
    }
    .row .right .subnumber{
        display: inline;
        margin:0 10px;
    }
    .row .right span{
        color: red;
        font-size: 16px;
    }
    .col{
        display: inline;
        float: right;
    }
</style>
<script>
    import  subNumber from '../SubComp/subNumber.vue';
    import  {getItem,setItem,subStrictItem,removeItem} from '../../kits/localStorageHelper.js';
    import  common from '../../kits/common.js';
    //6.0.2 注册commonVue.js(用来当商品数量改变时发送通知给app.vue改变图标数量) (app.vue和goodsinfo.vue不是父子关系所以不能直接传值，要通过一个公用vue传值)
    import {vueObj} from '../../kits/commonVue.js';
    export default{
        data(){
            return{
                selectedCount:0,//这是选择商品的总个数
                values:[],       //用来存储每条数据的switch中的值，只要选中了，里面存的就是true
                shopCarList:[]  //用来存储购物车中的商品的
            }
        },
        created(){
            this.initPageData();
        },
        methods:{
            //获取到数量选择器中的数值
            getCount(resObj){
                //1.0判断resObj的type类型
                if (resObj.type == 'add'){
                    //增加一个商品数量
                    this.add(resObj);
                    //2.0 更新shopcarlist中商品对应的数量加1
                    this.updateShopCarList(1,resObj.goodsid);

                    //发送通知给app.vue更改商品数量
                    vueObj.$emit('newEmit');

                }else if(resObj.type == 'substrict'){
                    //减少一个商品数量
                    subStrictItem(resObj.goodsid);
                    //2.0 更新shopcarlist中商品对应的数量
                    this.updateShopCarList(-1,resObj.goodsid);

                    //发送通知给app.vue更改商品数量
                    vueObj.$emit('newEmit');

                }

            },
            updateShopCarList(count,goodsid){
                //1.0找到商品的数据
                for(let i = 0;i<this.shopCarList.length;i++){
                    if (this.shopCarList[i].id == goodsid){
                        this.shopCarList[i].count = this.shopCarList[i].count + count;
                    }
                }
            },
            add(resObj){
                setItem({goodsid:resObj.goodsid,count:1});
            },
            //根据商品id获取商品数据
            initPageData(){
                //1.0从localStorage中获取所有的商品id
                //arr的数据格式：[{goodsid:1,count:1},{},{}]
                let arr = getItem();
                let goodsObj = {};  //负责将goodsid的值当做属性名称，count值当做属性值
                arr.forEach(item=>{
                   if(goodsObj[item.goodsid]){
                       //如果存在，则将count追加上去
                       let tmpcount = goodsObj[item.goodsid];
                       tmpcount += item.count;
                       goodsObj[item.goodsid] = tmpcount;
                   }else {
                       //如果不存在则直接设置到count上
                        goodsObj[item.goodsid] = item.count;
                   }
                });
                //1.0.1将goodsObj中的属性名称拿出来
                let idarr = [];
                for(let goodsidvalue in goodsObj){
                    idarr.push(goodsidvalue);
                }
                let ids = idarr.join(',');//将数组变成字符串，并且用','分隔


                //2.0请求api获取数据
                let url = common.apihost + '/api/goods/getshopcarlist/' + ids;
                let carList = [];
                this.$http.get(url).then(
                    res=>{
                        console.log(res.body);
                        //因为数据库版本问题，更新sql语句后对查询数据处理
                        for(var i = 0;i<res.body.message.length;i++) {
                            var state = false;
                            for(var n = 0;n<carList.length;n++){
                                if(carList[n].id == res.body.message[i].id){
                                    state = true;
                                }
                            }
                            if(!state){
                                res.body.message[i].thumb_path = common.imghost + res.body.message[i].thumb_path;
                                carList.push(res.body.message[i]);
                            }
                        }
                        //遍历carList数组传入count值，通过上面的goodsObj
                        carList.forEach(item=>{
                            item.count = goodsObj[item.id];

                            //初始化values数组，值全部设置为false
                            this.values.push(false);

                        });
                        this.shopCarList =carList;
                    },
                    res=>{
                        console.log('购物车列表请求失败');
                    }
                );
            },
            //统计选择商品的总价
            getTotalAmount(){
                let totalAmount = 0;
                this.values.forEach((item,index)=>{
                    if (item == true){
                        let goodsinfo = this.shopCarList[index] //获取当前选择的商品
                        //开始计算商品总价格
                        let amount = goodsinfo.count * goodsinfo.sell_price;
                        totalAmount+=amount;
                    }
                });
                return totalAmount;
            },
            //删除商品数据
            del(goodsid){
//                console.log(goodsid)
                //1.0 将shopcharlist中的数据删除
                let index = this.shopCarList.findIndex(c=>c.id == goodsid);
                if(index >= 0){
                    this.shopCarList.splice(index,1);
                }
                //2.0 删除localstorage中的数据
                removeItem(goodsid);

                //发送通知给app.vue更改商品数量
                vueObj.$emit('newEmit');
            }
        },
        computed:{  //计算属性，vue的双向数据绑定，这里的作用是当点击购物车旁边的switch时候触发计算
            //统计总价格
            settment(){
                //注意点：这个settment的计算属性是依赖于this.values数组的值的改变而会被重新触发计算
                //并且一定要在<remplate>中使用settment才会被触发
                //1.0统计当前选择的个数
                let trueArr = this.values.filter(v=>v==true);
                this.selectedCount = trueArr.length;

                //2.0计算价格并返回即可
                return this.getTotalAmount();
            }
        },
        components:{
            subNumber
        }
    }
</script>
